import imgs from "./imgs";
const drawUtils = {
  draw_rect_point: function (canvas, item, text = '1', draw = true) {
    const [x, y, w, h] = item
    const rect = new fabric.Rect({
      lockMovementX: true,
      lockMovementY: true,
      selectable: false,
      hasControls: false,
      top: 0,
      left: 0,
      width: w,
      height: h,
      fill: '#0F0', // 填充色：透明
      stroke: '#F00' // 边框颜色：黑色
    })
    const textObject = new fabric.Text(text, {
      fontSize: w >= h ? w / 2.2 : h / 2.2,
      fill: '#000',
      textAlign: 'center',
      lineHeight: h,
      width: w,
      left: 0,
      top: 0
    });
    const group = new fabric.Group([rect, textObject], {
      left: x,
      top: y,
      lockMovementX: true,
      lockMovementY: true,
      selectable: false,
      hasControls: false,

    });
    if (draw) {
      canvas.add(group);
    }

    return group
  },
  sortArea(rects, sortType = "xy") {
    const listArea = rects.map(item => {
      return {
        sortValue: item.position,
        target: item.target,
        position: null
      }
    })
    let allX = []
    let allY = []
    //设置排序值
    listArea.forEach(item => {
      let [x, y, w, h] = item.sortValue
      let targetX = null
      let targetY = null
      let centerX = x + (w / 2)
      let centerY = y + (h / 2)
      let allXLength = allX.length
      for (let i = 0; i < allXLength; i++) {
        let allXItem = allX[i]
        let start = allXItem.a1
        let end = allXItem.a2
        let value = allXItem.value
        if (centerX >= start && centerX <= end) {
          targetX = value
          break
        }
      }
      if (targetX == null) {
        targetX = x
        allX.push({
          a1: x,
          a2: x + w,
          value: x
        })
      }
      let allYLength = allY.length
      for (let i = 0; i < allYLength; i++) {
        let allYItem = allY[i]
        let start = allYItem.a1
        let end = allYItem.a2
        let value = allYItem.value
        if (centerY >= start && centerY <= end) {
          targetY = value
          break
        }
      }
      if (targetY == null) {
        targetY = y
        allY.push({
          a1: y,
          a2: y + h,
          value: y
        })
      }
      item.position = [targetX, targetY]
    })
    if (sortType === 'xy') {

      return listArea.sort((a1, a2) => {
        let [x, y] = a1.position
        let [x1, y1] = a2.position
        if (x - x1 === 0) {
          return y - y1
        }
        return x - x1
      });
    } else {
      return listArea.sort((a1, a2) => {
        let [x, y] = a1.position
        let [x1, y1] = a2.position
        if (y - y1 === 0) {
          return x - x1
        }
        return y - y1
      });
    }
  },

  getRect(list) {
    if (list.length === 0) {
      return
    }
    let [x0, y0, w0, h0] = list[0]
    let minX = x0;
    let minY = y0
    let maxX = x0 + w0
    let maxY = y0 + h0
    list.forEach(item => {
      let [x, y, w, h] = item
      maxX = Math.max(maxX, x + w)
      minX = Math.min(minX, x)

      maxY = Math.max(maxY, y + h)
      minY = Math.min(minY, y)
    })
    return [minX, minY, maxX - minX, maxY - minY]
  },
  draw_rect_student_code: function (canvas, items, title = "学号区域", draw = true) {
    if (items == null || items.length === 0) {
      return
    }
    const positions = items.map(item => {
      const selectItems = item.positions.map(p => {
        return p.position
      })
      return this.getRect(selectItems)
    });

    const maxRect = this.getRect(positions)
    let groups = []
    for (let i = 0; i < items.length; i++) {
      const item = items[i]
      const [cx, cy, cw, ch] = item.container
      const listItme = []
      for (let i = 0; i < item.positions.length; i++) {
        let position = item.positions[i];
        const [px, py, pw, ph] = position.position;
        const rect = new fabric.Rect({
          lockMovementX: true,
          lockMovementY: true,
          selectable: false,
          hasControls: false,
          top: 0,
          left: 0,
          width: pw,
          height: ph,
          fill: 'rgb(0,255,0)', // 填充色：透明
          strokeWidth: 0,
          stroke: '#F00' // 边框颜色：黑色
        })
        const text = position.value
        const textObject = new fabric.Text(text, {
          fontSize: 20,
          fill: '#000',
          textAlign: 'center',
          lineHeight: ph,
          width: pw,
          left: 0,
          top: 0
        });
        const positionGroup = new fabric.Group([rect, textObject], {
          left: px - cx,
          top: py - cy,
          lockMovementX: true,
          lockMovementY: true,
          selectable: false,
          hasControls: false,
        })
        listItme.push(positionGroup)
      }
      const group = new fabric.Group(listItme, {
        left: cx,
        top: cy,
        lockMovementX: true,
        lockMovementY: true,
        selectable: false,
        hasControls: false,
      })

      groups.push(group)
    }
    const maxRectGroup = new fabric.Group(groups.map(item => {
      item.left = item.left - maxRect[0]
      item.top = item.top - maxRect[1]
      return item
    }), {
      left: maxRect[0],
      top: maxRect[1],
      width: maxRect[2],
      height: maxRect[3],
      lockMovementX: true,
      lockMovementY: true,
      selectable: false,
      hasControls: false,
    })
    if (draw) {

      canvas.add(maxRectGroup);
    }
    maxRectGroup.items = items
    return maxRectGroup

  },
  draw_select_single_item_by_config(canvas, data, draw = true) {
    const {x, y} = data
    const {w, h, s, n, f} = data

    const items = []
    let maxH = 0;
    let maxW = 0;
    let createXy = null
    if (f === 'h') {
      createXy = (index) => {
        return [x + ((w + s) * (index)), y]
      }
    } else {
      createXy = (index) => {
        return [x, y + ((h + s) * (index))];
      }
    }

    const rects = []
    for (let i = 0; i < n; i++) {
      rects.push([...createXy(i), w, h]);
    }
    return this.draw_select_single_item_by_items(canvas, rects, false, draw)
  },
  onDeleteButton(object, canvas, hiddenControls = true) {
    const _this = this
    object.hasControls = true
    object.selectable = true
    object.lockMovementX = false
    object.lockMovementY = false
    if (hiddenControls) {
      object.controls = {}
    }
    delete object.controls.mtr
    // console.log(object.controls)
    object.controls.deleteControl = new fabric.Control({
      x: 0.5,
      y: -0.5,
      offsetY: 0,
      cursorStyle: 'pointer',
      mouseUpHandler: (eventData, transform) => {
        object.isDelete = true
        canvas.remove(object)
      },
      render: (ctx, left, top, styleOverride, fabricObject) => {
        var size = 20;
        ctx.save();
        ctx.translate(left, top);
        ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
        ctx.drawImage(imgs.deleteImg, -size / 2, -size / 2, size, size);
        ctx.restore();
      },
      cornerSize: 20
    })


    // object.addOther = function (canvas) {
    //   const x = this.left
    //   const y = this.top - 17
    //   let drawDeleteIcon = _this.drawDeleteIcon(x, y);
    //   canvas.on("mouse:down", (e) => {
    //     if (e.absolutePointer) {
    //       if (drawDeleteIcon.containsPoint(e.absolutePointer)) {
    //         object.isDelete = true
    //         canvas.remove(object)
    //       }
    //     }
    //   })
    //   object.removeOther = () => {
    //     canvas.remove(drawDeleteIcon)
    //   }
    //   canvas.add(drawDeleteIcon)
    //   object.moveCallback = () => {
    //     drawDeleteIcon.left = this.left
    //     drawDeleteIcon.top = this.top - 17
    //     //重新计算
    //     drawDeleteIcon.setCoords()
    //     canvas.renderAll()
    //   }
    // };

  },
  drawDeleteIcon(x, y) {

// 创建X标记
    let text = new fabric.Text("删除", {
      top: y,
      left: x,
      lockMovementX: true,
      lockMovementY: true,
      selectable: true,
      hasControls: false,
      width: 100,
      fontSize: 15,
      fill: '#00F',
    });
    text.isButton = true
    return text
  },
  draw_subjective(canvas, items, draw = true) {

    if (items == null) {
      items = []
    }
    let targetObject = {
      utils: this,
      canvas: canvas,
      items: [],
      pushPosition(position, question) {
        let rect1 = new fabric.Rect({
          lockMovementX: false,
          lockMovementY: false,
          selectable: true,
          hasControls: true,
          top: position[1],
          left: position[0],
          width: position[2],
          height: position[3],
          fill: 'rgba(0,255,0,0)', // 填充色：透明
          strokeWidth: 1,
          stroke: '#F00' // 边框颜色：黑色
        });
        this.push(rect1, question)
      },
      push: function(rect, question, render= true) {

        // rect.fill = 'black'
        let text = new fabric.Textbox(`${question.paperIndex}题-${question.score}分`, {
          fill: '#F00',
          fontSize: 30,
          left: 0,
          top: 0,
          textAlign: 'center',
          verticalAlign: 'middle',

          width: rect.width,
          height: rect.height
        });
        const left = rect.left
        const top = rect.top
        rect.left = 0
        rect.top = 0
        let group = new fabric.Group([text,rect],
          {
            left: left,
            top: top,
            lockMovementX: false,
            lockMovementY: false,
            selectable: true,
            hasControls: true,
          });
        this.items.push(group)
        group.custom_type = 'subjective';

        this.utils.onDeleteButton(group, this.canvas, false);
        group.question = question

        if (render) {
          this.canvas.add(group)
        }

      },
      add: function() {
        this.items.forEach(item => {
          this.canvas.add(item)
        })
      },
      removeObject: function(rect){
        this.clear()
        this.items = this.items.filter(i => {
          return rect !== i
        })
        this.add()
      },
      clear: function () {
        this.items.forEach(item => {
          canvas.remove(item)
        })
      },
      consolePositions: function(canvasIndex) {

        const map = {}
        this.items.forEach(q => {
          const question = q.question
          const key = question.questionId + question.questionIndex
          const o = map[key] || {
            questionId: question.questionId,
            questionIndex: question.questionIndex,
            templateIndex: canvasIndex,
            positions: []
          }
          o.positions.push({
            value: 'content',
            position: [Math.max(0, q.getRealLeft()), Math.max(0, q.getRealTop()), q.getScaledWidth(), q.getScaledHeight()]
          })
          map[key] = o
        })
        const rects = []
        for (let mapKey in map) {
          rects.push(map[mapKey])
        }
        return rects
      }
    };
    for (let i = 0; i < items.length; i++) {
      let item = items[i];
      let length = item.positions.length;
      let score = item.score
      let paperIndex = item.paperIndex
      for (let j = 0; j < length; j++) {
        const p = item.positions[j];
        const position = p.position
        targetObject.pushPosition(position, item)
      }
    }




    if (draw) {
      targetObject.add()
    }
    return targetObject;
  },
  draw_objective(canvas, area, draw = true) {
    const questionAreaItems = area.questionAreaItems
    let items = []
    const otherAddObject = []
    for (let i = 0; i < questionAreaItems.length; i++) {
      const data = questionAreaItems[i]
      let positions = data.positions;
      let rects = []
      let rectPositions = []
      for (let j = 0; j < positions.length; j++) {
        let positionObject = positions[j]
        const position = positionObject.position
        rectPositions.push(position)
        let rect = new fabric.Rect({
          left: position[0],
          top: position[1],
          width: position[2],
          height: position[3],
          fill: 'rgba(125,255,125,0.5)', // 填充色：透明
          lockMovementX: true,
          lockMovementY: true,
          selectable: false,
          hasControls: false,
        });
        otherAddObject.push(new fabric.Textbox(positionObject.value, {
          top: position[1],
          left: position[0],
          lockMovementX: true,
          lockMovementY: true,
          selectable: false,
          textAlign: 'center',
          hasControls: false,
          width: position[2],
          fontSize: position[3] * 0.8,
          fill: '#00F',
        }))
        rects.push(rect)
      }
      let [_x, _y, _w, _h] = this.getRect(rectPositions);
      otherAddObject.push(new fabric.Textbox(data.paperIndex ? `题号:${data.paperIndex}-${data.score}分`: "", {
        top: _y - (_h * 1.5),
        left: _x,
        lockMovementX: true,
        lockMovementY: true,
        textAlign: 'left',
        selectable: false,
        hasControls: false,
        width: _w,
        fontSize: _h * 1.5,
        fill: '#ff0000',
      }))
      let group = new fabric.Group(rects.map(item => {
        item.left = item.left - _x
        item.top = item.top - _y
        return item
      }), {
        left: _x,
        top: _y,
        lockMovementX: true,
        lockMovementY: true,
        selectable: false,
        hasControls: false,
      });
      group.saveRect = [_x, _y, _w, _h]
      items.push(group)
    }

    // let [__x,__y,__w,__h] = this.getRect(items.map(item => item.saveRect));
    // let maxGroup = new fabric.Group(items.map(item => {
    //   item.left = item.left - __x
    //   item.top = item.top - __y
    //   return item
    // }),
    //   {
    //     left: __x,
    //     top: __y,
    //     lockMovementX: true,
    //     lockMovementY: true,
    //     selectable: false,
    //     hasControls: false,
    //   });
    // maxGroup.items = area
    if (draw) {
      items.forEach(rect => {
        canvas.add(rect)
      })

    }
    return {
      items: area,
      rects: items,
      add: () => {
        items.forEach(rect => {
          canvas.add(rect)
        })
        otherAddObject.forEach(t => {
          canvas.add(t)
        })
      },
      clear: () => {
        items.forEach(rect => {
          canvas.remove(rect)
        })
        otherAddObject.forEach(t => {
          canvas.remove(t)
        })
      }
    };
    // draw_select_single_item_by_items

  },
  draw_select_single_item_by_items(canvas, items, ai, draw = true) {
    let [_x, _y, _w, _h] = this.getRect(items);
    const rects = []
    for (let i = 0; i < items.length; i++) {
      const [x, y, w, h] = items[i]
      let rect = new fabric.Rect({
        lockMovementX: true,
        lockMovementY: true,
        selectable: false,
        hasControls: false,
        left: x,
        top: y,
        width: w,
        height: h,
        fill: 'rgba(0,255,0,0.5)', // 填充色：透明
        strokeWidth: 0,
        stroke: '#F00' // 边框颜色：黑色
      });
      rects.push(rect)
    }
    let group = new fabric.Group(rects.map(item => {
      item.left = item.left - _x
      item.top = item.top - _y
      return item
    }), {
      left: _x,
      top: _y,
      width: _w,
      height: _h,
      lockMovementX: false,
      lockMovementY: false,
      selectable: true,
      hasControls: true,
    });
    if (_w > _h) {
      group.fangxiang = "h"
    } else {
      group.fangxiang = "s"
    }
    group.ai = ai
    if (draw) {
      canvas.add(group);
    }
    group.toColor = function (color) {
      rects.forEach(item => {
        item.fill = color
      })
    };
    group.consoleRectItems = function () {
      let length = this.getObjects().length;
      let objects = this.getObjects();
      const rects = []
      for (let i = 0; i < length; i++) {
        let object = objects[i]
        rects.push([object.getRealLeft(), object.getRealTop(), object.width * this.scaleX, object.height * this.scaleY])
      }
      return rects
    };
    return group
  }

};
if (Vue) {
  Vue.prototype.$draw = drawUtils
} else {
  window.drawRect_point = drawUtils
}

export default drawUtils
